package fr.cohen.image.ftp;

import java.awt.MediaTracker;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.regex.Pattern;

import javax.swing.ImageIcon;
import javax.swing.JLabel;

import fr.cohen.exception.ImageException;
import fr.cohen.factory.ImageFactory;
import fr.cohen.image.CohenImage;
import fr.cohen.image.ImageRepository;

public abstract class AbstractImageRepository implements ImageRepository, Runnable {

	protected String root = null;
	protected List<String> names;
	protected static int rang = 0;
	protected Proxy proxy = null;
	protected  Pattern pattern;
	private BlockingQueue<CohenImage> images;

	protected AbstractImageRepository(){

		images = new LinkedBlockingQueue<CohenImage>(3);
	}


	public void connect(String user, String password, String site, int port, String proxy, int proxyPort)
	throws ImageException {

		try {

			root = "ftp://" + user + ":" + password + "@" + site + ":" + port;
			URL url = new URL(root);

			if(proxy == null || proxyPort <= 0){

				this.proxy = null;
			}
			else{

				this.proxy = new Proxy(
					Proxy.Type.HTTP,
					new InetSocketAddress(proxy, proxyPort)
				);
			}

			System.out.println("Connected : " + root);
			names = this.refresh(url);
			Collections.shuffle(names);

			Thread thread = new Thread(this);
			thread.start();
		}
		catch (Exception e) {
			throw new ImageException(e);
		}

	}

	public CohenImage next() throws ImageException {

		CohenImage image;
		try {

			image = images.take();
		}
		catch (InterruptedException e) {

			throw new ImageException(e);
		}

		return image;
	}

	protected abstract List<String> refresh(URL url) throws IOException;


	public void run() {

		while(true){
			try {

				int id = 0;
				for(String name : names){

					CohenImage image = this.download(name, id);
					images.put(image);
				}
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private CohenImage download(String name, int id) throws Exception {

		URL url = new URL(
			root + "/" + URLEncoder.encode(name, "UTF-8").replace("+", "%20")
		);
		System.out.println(url);
		ImageIcon icon = new ImageIcon(url);
		MediaTracker tracker = new MediaTracker(new JLabel());
		tracker.addImage(icon.getImage(), id);
		tracker.waitForID(id);

		CohenImage image = ImageFactory.getFactory().createImage(name, icon);

		icon = null;

		return image;
	}
}
